package com.example.studentcoursesysteam.Controller;

import com.example.studentcoursesysteam.Bean.Course;
import com.example.studentcoursesysteam.Repository.CourseRepository;
import com.example.studentcoursesysteam.Repository.StudentCourseRepository;
import com.example.studentcoursesysteam.Repository.StudentRepository;
import com.example.studentcoursesysteam.Repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    StudentRepository studentRepository;
    @Autowired
    CourseRepository courseRepository;
    @Autowired
    StudentCourseRepository studentCourseRepository;
    @Autowired
    TeacherRepository teacherRepository;
    @RequestMapping("/insertCourse")
    public String insertCourse(Course course){
        if (!courseRepository.existsByCode(course.getCode())){
            courseRepository.save(course);
            return "添加选课成功";
        }else
            return "课程号已存在，添加失败";
    }

    @RequestMapping("/deleteCourse")
    public String deleteCourse(String code){
        if (!studentCourseRepository.existsByCourseCode(code)){
            courseRepository.getDeleteByCode(code);
            return "删除成功";
        }else
            return "已有学生选该门课，无法删除";
    }

    @RequestMapping("/updateCourse")
    public String updateCourse( Course course) {
        courseRepository.save(course);
        return "修改成功";
    }

    @RequestMapping("/selectCourse")
    public Page<Course> selectCourse() {
        Pageable pageable=PageRequest.of(0, 20,Sort.Direction.ASC, "code");
        Page<Course> courseList=courseRepository.findAll(pageable);
        return courseList;
    }

    @RequestMapping("/selectCourseName")
    public Page<Course> selectCourseName(String name) {
        Pageable pageable= PageRequest.of(0,20,Sort.Direction.ASC, "code");
        Page<Course> courseList=courseRepository.findByNameLike("%"+name+"%",pageable);
        return courseList;
    }
}
